<template>
  <div>
    <van-tabs v-model="active" sticky @change="tabChange">
      <van-tab title="我的考试" name="tab1">
        <van-pull-refresh
          v-model="firstTabLoading"
          :class="$style.refreshContainer"
          @refresh="onRefresh('tab1')"
        >
          <div
            v-if="
              waitExamingList.length > 0 || nextExamingList.length > 0 || examingList.length > 0
            "
          >
            <div v-if="waitExamingList.length > 0" :class="$style.space">待考试</div>
            <div
              v-for="item in waitExamingList"
              :key="item.id"
              :class="$style.examContainer"
              @click="joinExam(item.paperId, 'noexaming')"
            >
              <div :class="$style.examTextContainer">
                <div :class="$style.examtitle">
                  {{ item.title }}
                  <van-tag color="#3EAD68" :class="$style.examTag">可考试</van-tag>
                </div>
                <div :class="$style.examGrade">
                  {{ item.duration }}分钟 满分：{{ item.totalScore }}分
                </div>
                <div :class="$style.examSubmit">
                  {{ timeJoin(item.startTime, item.endTime) }}
                </div>
              </div>
            </div>
          </div>
          <van-empty v-else description="暂无考试数据" />
        </van-pull-refresh>
      </van-tab>

      <van-tab title="我的成绩" name="tab2">
        <van-pull-refresh
          v-model="secondTabLoading"
          :class="$style.refreshContainer"
          @refresh="onRefresh('tab2')"
        >
          <van-list
            v-model="loading"
            :finished="noMore"
            finished-text="没有更多了"
            @load="getMyScore"
          >
            <div>
              <van-row :class="$style.header">
                <van-col span="6">
                  <div :class="[$style.headerNumber, $style.passCount]">
                    {{ scoreStatics.passCount }}
                  </div>
                  <div :class="$style.headerText">及格</div>
                </van-col>
                <van-col span="6">
                  <div :class="[$style.headerNumber, $style.noPassCount]">
                    {{ scoreStatics.notPassCount }}
                  </div>
                  <div :class="$style.headerText">不及格</div>
                </van-col>
                <van-col span="6">
                  <div :class="[$style.headerNumber, $style.passRate]">
                    {{ scoreStatics.passRate }}%
                  </div>
                  <div :class="$style.headerText">通过率</div>
                </van-col>
                <van-col span="6">
                  <div :class="[$style.headerNumber, $style.waitCount]">
                    {{ scoreStatics.waitCorrectCount }}
                  </div>
                  <div :class="$style.headerText">待批改</div>
                </van-col>
              </van-row>

              <template v-for="item in scoreList">
                <div
                  :key="item.id"
                  :class="item.status != 3 ? $style.examContainer : $style.noexamContainer"
                >
                  <van-row>
                    <van-col span="18" :class="$style.examTextContainer">
                      <div :class="$style.examtitle">{{ item.title }}</div>
                      <div :class="$style.examGrade">
                        {{ item.duration }}分钟 满分：{{ item.totalScore }}分
                      </div>
                      <div :class="$style.examSubmit">
                        {{ item.status != 3 ? `${timeConvert(item.endTime)} 交卷` : '考试未参加' }}
                      </div>
                    </van-col>
                    <van-col
                      v-if="item.status === 1"
                      span="6"
                      :class="$style.examTextScore"
                      style="font-size: 12px; color: #f9963b"
                    >
                      待批改
                    </van-col>
                    <van-col
                      v-else-if="item.status === 2 && item.isPass == 1"
                      span="6"
                      :class="$style.examTextScore"
                    >
                      {{ item.score }}<span style="font-size: 12px">分</span>
                    </van-col>
                    <van-col
                      v-else-if="item.status === 2 && item.isPass == 0"
                      span="6"
                      :class="$style.examTextScore"
                      style="color: #ff4444"
                    >
                      {{ item.score }}<span style="font-size: 12px">分</span>
                    </van-col>
                    <van-col
                      v-else-if="item.status === 3"
                      span="6"
                      :class="$style.examTextScore"
                      style="font-size: 12px; color: #ff4444"
                    >
                      缺考
                    </van-col>
                  </van-row>
                </div>
              </template>
            </div>
          </van-list>
        </van-pull-refresh>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import { Tab, Tabs, Col, Row, Tag, PullRefresh, Empty, List } from 'vant';
// import { openLink } from '@/helpers/client-jsapi';
import { dataTransform, dateFormat } from '@/helpers/data-transform';

import { GetpaperList, GetPaperStatistics, GetPaperWait } from '@/apis';
export default {
  name: 'Home',
  components: {
    'van-tabs': Tabs,
    'van-tab': Tab,
    'van-row': Row,
    'van-col': Col,
    'van-tag': Tag,
    'van-pull-refresh': PullRefresh,
    'van-list': List,
    'van-empty': Empty,
  },
  data() {
    return {
      /**第一个tab的loading */
      firstTabLoading: false,
      /**第二个tab的loading */
      secondTabLoading: false,
      /**待考试 */
      waitExamingList: [],
      /**未来考试 */
      nextExamingList: [],
      /**正在考试 */
      examingList: [],
      /**考试倒计时 */
      examingTime: '',
      /**考试倒计时函数 */
      examingTimeSetTimeOut: '',
      /**我的成绩列表 */
      scoreList: [],
      /**统计数据 */
      scoreStatics: {},
      active: 'tab1',
      totalPage: 1,
      pageIndex: 1,
      pageSize: 10,
      loading: false,
      disabeld: false,
    };
  },
  computed: {
    /** 秒转分钟 */
    secToMin() {
      return (sec) => (sec ? Math.floor(parseInt(sec) / 60) : '-');
    },
    /** 开始时间+结束时间 */
    timeJoin() {
      return (start, end) =>
        `${start ? start.split(' ')[0].replace(/-/g, '/') : ''} - ${
          end ? end.split(' ')[0].replace(/-/g, '/') : ''
        } `;
    },
    /** 时间转换 */
    timeConvert() {
      return (time) => `${time ? time.replace(/-/g, '/') : ''}`;
    },
    noMore() {
      return this.pageIndex > this.totalPage;
    },
  },

  mounted() {
    this.active = this.$router.history.current.query.tab
      ? this.$router.history.current.query.tab
      : 'tab1';
    this.pageIndex = 1;
    this._getPaperWaitList();
    this._getPaperStatistics();
    // if (this.active == 'tab1') this.getMyScore(); //防止重复加载第一页
  },
  methods: {
    /**初始化数据 */
    initData() {
      this.waitExamingList = [];
      this.nextExamingList = [];
      this.examingList = [];
      this.examingTime = '';
      clearTimeout(this.examingTimeSetTimeOut);
    },
    _getPaperWaitList() {
      return GetPaperWait().then((res) => {
        var todayStr = dateFormat('yyyy-MM-dd', new Date());
        res.data &&
          res.data.length > 0 &&
          res.data.forEach((item) => {
            if (
              this._compareDate(todayStr, item.startTime) &&
              this._compareDate(item.endTime, todayStr)
            ) {
              this.waitExamingList.push(item);
            }
          });
        return true;
      });
    },
    _compareDate(d1, d2) {
      return d1 >= d2;
    },
    _getPaperStatistics() {
      return GetPaperStatistics().then((res) => {
        this.scoreStatics = res.data;
      });
    },
    /** 获取我的成绩列表 */
    getMyScore(refresh) {
      if (this.disabeld) return;
      if (!refresh && this.noMore) return;
      this.disabeld = true;
      // if (this.secondTabLoading) return;
      return GetpaperList({ page: this.pageIndex, size: this.pageSize }).then((res) => {
        var data = res.data;
        if (this.pageIndex === 1) {
          this.totalPage = data.totalPage;
          this.scoreList = data.list;
        } else {
          this.scoreList = [...this.scoreList, ...data.list];
        }
        this.pageIndex = this.pageIndex + 1;
        this.loading = false;
        this.disabeld = false;
      });
    },
    /** 加入考试 */
    joinExam(id, type) {
      if (type === 'noexaming') {
        this.$router.push(`/exam?id=${id}`);
      }
    },
    /** 下拉刷新 */
    onRefresh(type) {
      if (type === 'tab1') {
        this.waitExamingList = [];
        this._getPaperWaitList().then(() => (this.firstTabLoading = false));
        return;
      }
      this.pageIndex = 1;
      this.scoreList = [];
      this.getMyScore(true).then(() => (this.secondTabLoading = false));
      this._getPaperStatistics();
      return;
    },

    /** 倒计时 */
    dataConvert(time, item) {
      this.examingTimeSetTimeOut = setTimeout(() => {
        if (time > 0) time--;
        this.examingTime = dataTransform(time, 2);
        if (time === 0) {
          // const isCacheQuestion = !!window.localStorage.getItem(`paper${item.id}`);
          this.dataConvert(time, item);
        } else {
          this.dataConvert(time, item);
        }
      }, 1000);
    },
    /** tab改变事件 */
    tabChange(name) {
      this.$router.replace(`/?tab=${name}`);
    },
  },
};
</script>

<style lang="less" module>
@import '~vant/lib/style/var.less';
@import '~@scf/ding-style-less/var.less';

div::-webkit-scrollbar {
  width: 0;
}

.refreshContainer {
  height: 100%;
  min-height: 80vh;
  padding-bottom: 10px;
}

.header {
  width: 345px;
  height: 80px;
  background: #ffffff;
  border-radius: 6px;
  margin: 10px auto 0;
  text-align: center;
}

.headerNumber {
  width: 86.25px;
  height: 50px;
  font-size: 18px;
  color: #666666;
  line-height: 50px;
}
.passCount {
  color: #44b66c;
}
.noPassCount {
  color: #ff081f;
}
.passRate {
  color: #198aff;
}
.waitCount {
  color: #f9b816;
}
.headerText {
  font-size: 12px;
  color: #b5b5b5;
}

.examContainer {
  background: #ffffff;
  border-radius: 6px;
  width: 345px;
  margin: 10px auto 0;
  padding: 0 15px;
}

.noexamContainer {
  border-radius: 6px;
  width: 345px;
  margin: 10px auto 0;
  padding: 0 15px;
  background: rgba(255, 68, 68, 0.05);
  border: 0.5px solid rgba(255, 68, 68, 0.5);
}
.examTextContainer {
  padding: 15px 0;
  height: 100px;
}

.examTextScore {
  height: 100px;
  line-height: 100px;
  font-size: 20px;
  color: #3ead68;
  text-align: center;
}

.examTag {
  font-weight: normal;
  margin-left: 10px;
  font-size: 10px;
  // color: #3ead68;
  transform: translateY(-1px);
}

.examtitle {
  font-weight: 600;
  font-size: 14px;
  color: #333333;
}

.examRight {
  padding: 7px 0;
  text-align: right;
}

.examRightText {
  font-size: 12px;
  color: #969799;
}

.examRightTime {
  font-size: 14px;
  color: #f9963b;
}

.examGrade {
  padding: 7px 0;
  font-size: 12px;
  color: #666666;
}

.examSubmit {
  font-size: 12px;
  color: #969799;
}

.space {
  height: 12px;
  font-size: 12px;
  color: #969799;
  margin: 20px 0px 10px 15px;
}
</style>
